/// <reference path="../../index.d.ts" />
const Service = require("egg").Service

let helper = require("../extend/helper")
let errLogTime = 0
class WechatUser extends Service {

	constructor(ctx) {
		super(ctx)
		this.serverConfig = this.config.serverConfig
		this.ApplicationUser = this.app.model.ApplicationUser
		this.UserKfMsg = this.app.model.UserKfMsg
	}

	/**
	 * 获取用户openid
	 */
	async getUserOpenId(oid) {
		let data = await this.ApplicationUser.findOne({
			where: {
				id: oid
			},
			attributes: ["openid"]
		})
		return data && data.openid
	}

	/**
	 * context 由当前系统环境决定
	 * imgHref 图文链接
	 * 已经回复的消息 状态
	 * @param {string} openid 
	 * @param {{textContent:string,imgTitle:string,imgDesc:string,imgHref:string,promTitle:string,promPath:string,imgPath:string}} content 
	 */
	async	sendMsg(openid, content, msgType, oid) {
		let ctx = this.ctx
		let res
		if (msgType == 1) { // 文本
			res = await ctx.wechatAccount.sendText(openid, content.textContent)
		} else if (msgType == 2) {// 图片this.serverConfig.i
			// {title:string,description:string,url:string,picurl:string}>}
			if (ctx.wechat.app_type <= 2) {
				res = await ctx.wechatAccount.sendPromNews(openid, {description: content.imgDesc, title: content.imgTitle, thumb_url: this.serverConfig.imgServer + content.imgPath, url: content.imgHref})
			} else {
				res = await ctx.wechatAccount.sendNews(openid, [{description: content.imgDesc, title: content.imgTitle, url: content.imgHref, picurl: this.serverConfig.imgServer + content.imgPath}])
			}
			// console.log(this.serverConfig.imgServer + content.imgPath)
		} else {
			let obj = await this.uploadImg(content.imgPath)
			if (!obj) {
				return false
			}
			res = await ctx.wechatAccount.sendPromMsg(openid, {
				title: content.promTitle,
				pagepath: content.promPath,
				appid: ctx.wechatAccount.appid,
				thumb_media_id: obj.media_id
			})
		}
		if (!res || res.errcode == 0) {
			// 成功发送保存记录
			await this.UserKfMsg.update({respone_stat: 1}, {
				where: {
					oid: oid
				}
			})
			await this.UserKfMsg.create({oid: 0, to_user: oid, respone_stat: 1, msg: JSON.stringify(content)})
			return true
		} else {
			ctx.logger.warn(res)
			ctx.logger.warn(content)
			return false
		}
	}
	/**
	 *  上传资源到微信服务器
	 */
	async uploadImg(imgPath) {
		let ctx = this.ctx
		let fullPath = ctx.service.server.checkImgPath(imgPath)
		if (fullPath) {
			let data = await ctx.wechatAccount.uploadMedia(fullPath, "image")
			return data
		}
		throw new Error("上传失败错误")
	}

	/* 	async	findUserName(name) {
			let data = await this.ApplicationUser.findAll({
				where: {
					nickname: {
						$like: name
					}
				},
				attributes: ["id"]
			})
			return data.map(o => o.id)
		} */

	checkMsgObj(obj, msgType) {
		if (msgType == 1) {
			this.ctx.validate({"textContent": "string"}, obj)
		}
		else if (msgType == 2) {
			this.ctx.validate({"imgTitle": "string", "imgDesc": "string", "imgHref": "string", "imgPath": "string"}, obj)
		}
		else if (msgType == 3) {
			this.ctx.validate({"promTitle": "string", "promPath": "string", "imgPath": "string"}, obj)
		}
		return true
	}

	/**
	 *  微信公众号拉取用户信息
   */
	async fetchUserInfo(openid) {
		let user = await this.ApplicationUser.findOne({
			where: {
				openid
			}
		})
		if (!user) {
			let userData = await this.ctx.wechatAccount.getUser(openid)
			if (userData && userData.code == undefined) {
				user = await this.ApplicationUser.create({
					aid: this.ctx.wechat.aid,
					subscribe: userData.subscribe,
					create_at: Date.now(),
					last_login: Date.now(),
					unionid: userData.unionid,
					nickname: userData.nickname,
					openid,
					stat: 1,
					language: userData.language,
					province: userData.province,
					city: userData.city,
					country: userData.country,
					headimg_url: userData.headimgurl,
					subscribe_time: userData.subscribe_time,
					sex: userData.sex
				})
			}
		}
		return user
	}
	/**
	 * 基础的用户信息
	 * @param {*} oid 
	 */
	async getUserBaseInfo(oid) {
		let wxUser = await this.ApplicationUser.find({
			where: {id: oid},
			attributes: ["headimg_url", "nickname", "openid"]
		})
		wxUser = wxUser || {}
		return {nickName: wxUser.nickname, avatar: wxUser.headimg_url}
	}

	async countLogin() {
		let UserLogin = this.ctx.model.UserLogin
		let key = "userLogin#" + this.ctx.userInfo.oid
		await helper.later(5000 * Math.random())
		await this.service.db.getSet(key, {
			noExist: async () => {// 初始化协议
				let obj = {
					oid: this.ctx.userInfo.oid,
					login_time: Date.now(),
					aid: this.ctx.userInfo.aid,
				}
				try {
					await UserLogin.upsert({// 确保不存在重复的
						oid: this.ctx.userInfo.oid,
						login_time: Date.now(),
						aid: this.ctx.userInfo.aid,
					}, {fields: ["login_time"]})
					return obj
				} catch (error) {
					errLogTime++
					if (errLogTime < 3) {
						this.ctx.logger.error(error)
					}
				}
			},
			expire: helper.todayRemaining()// 今天过期
		})
	}
}
module.exports = WechatUser